import axios from 'axios'

// axios配置
axios.defaults.timeout = 5000;
axios.defaults.baseURL = '';

// http-request拦截器
axios.interceptors.request.use(
    config => {
        const token = "xxx";
        config.data = JSON.stringify(config.data);
        config.headers = {
            'Content-Type': 'application/x-www.form-urlencoded'
        };
        if (token) {
            config.params = {'token': token}
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http-response 拦截器
axios.interceptors.response.use(
    response => {
        if (response.data.errCode == 2) {
            console.log("错误")
        }
        return response;
    },
    error => {
        console.error(error);
        return Promise.reject(error)
    }
);

/**
 * 公共Get请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * 公共Post请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(res => {
                resolve(res.data)
            }, err => {
                reject(err)
            })
    })
}